package com.fifth.permission.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fifth.common.pojo.dto.CommonResult;
import com.fifth.common.pojo.entity.Permission;
import com.fifth.permission.mapper.PermissionMapper;
import com.fifth.permission.service.PermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @作者：刘壬杉
 * @创建时间 2022/8/31 11:53
 **/
@Service
public class PermissionImpl implements PermissionService {
    @Autowired
    private PermissionMapper permissionMapper;

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 根据empid查询对应权限信息
     * @param empid
     * @return
     */
    @Override
    public List<String> findByEmpid(String empid) {
        return permissionMapper.findByEmpid(empid);
    }

    /**
     * 根据empid查询对应权限全部信息(前端调用)
     * @param token
     * @return
     */
    @Override
    public CommonResult findAllByEmpid(String token) {
        String value = redisTemplate.opsForValue().get(token);
        Map map = JSON.parseObject(value, Map.class);
        JSONObject user = (JSONObject) map.get("user");
        List<Permission> permissionList = permissionMapper.findAllByEmpid(user.getString("id"));
        //System.out.println(permissionList);
        //设置层级关系
        List<Permission> firstMenus = new ArrayList<>();
        for (Permission first : permissionList) {
            if (first.getPid().equals("0")) {
                firstMenus.add(first);
            }
        }
        //为一级菜单设置二级菜单
        for (Permission first : firstMenus) {
            //根据一级菜单id 查询 该菜单得二级菜单。如果出现不确定有几级菜单 那么我们可以使用方法得递归调用
            first.setChildren(findChildren(permissionList, first.getId()));

        }
        return new CommonResult(2000,"查询成功",firstMenus);
    }

    //查询所有的权限
    @Override
    public List<Permission> selectAllPermission() {
        QueryWrapper wrapper=new QueryWrapper();
        List list = permissionMapper.selectList(wrapper);
        return list;
    }


    //方法递归
    private List<Permission> findChildren(List<Permission> permissionList, String id) {
        List<Permission> children = new ArrayList<>();
        for (Permission p : permissionList) {
            if (p.getPid().equals(id)) {
                children.add(p);
            }
        }
        for (Permission child : children) {
            child.setChildren(findChildren(permissionList, child.getId()));
        }
        return children;
    }
}
